package com.itachi.common.swagger.config;


import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnProperty(name = "swagger.enabled",matchIfMissing = true)
@Import({SwaggerBeanPostProcessor.class,SwaggerWebConfiguration.class})
public class SwaggerAutoConfiguration {

    private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error","/actuator/**");

    @Bean
    public Docket docket(SwaggerProperties properties)
    {
        if (properties.getBasePath().isEmpty()){
            properties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        properties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));
        if (properties.getExcludePath().isEmpty()){
            properties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
        }
        List<Predicate<String>> excludePath = new ArrayList<>();
        properties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
        ApiSelectorBuilder apis = new Docket(DocumentationType.SWAGGER_2).host(properties.getHost())
                .apiInfo(apiInfo(properties)).select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()));
        properties.getBasePath().forEach(e -> apis.paths(PathSelectors.ant(e)));
        properties.getExcludePath().forEach(e -> apis.paths(PathSelectors.ant(e).negate()));
        return apis.build().securitySchemes(securitySchemes()).securityContexts(securityContexts()).pathMapping("/");

    }


    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的全局鉴权策略
     *
     * @return
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 安全模式，这里指定token通过Authorization头请求头传递
     * @return
     */
    private List<SecurityScheme> securitySchemes()
    {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }


    private ApiInfo apiInfo(SwaggerProperties properties)
    {
        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .license(properties.getLicense())
                .licenseUrl(properties.getLicenseUrl())
                .termsOfServiceUrl(properties.getTermsOfServiceUrl())
                .contact(new Contact(properties.getContact().getName(), properties.getContact().getUrl(), properties.getContact().getEmail()))
                .version(properties.getVersion())
                .build();
    }


}
